package edu.sandau.b230151.b23015109.controller;

import edu.sandau.b230151.b23015109.model.Student;

import edu.sandau.b230151.b23015109.repository.StudentRepository;
import edu.sandau.b230151.b23015109.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


import java.util.*;

@Controller
@RequestMapping("student")
public class Studentcontroller {
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentRepository studentRepository;
//    @RequestMapping("search")
//    public String search(ModelMap map,Student student){
//        if("".equals(student.getName())){
//            student.setName(null);
//
//        }
////        List<Student> students = studentRepository.findByNameOrAge(student.getName(),student.getAge());
//        List<Student> students = studentRepository.findAll(Example.of(student));
//        map.put("studentList",students);
//        return "list";
//    }
//    private static Map<String,Student> students=new HashMap<>();
//    static {
//    Student s1=new Student("jack","1");
//    students.put(s1.getId(),s1);
//    Student s2=new Student("ack","2");
//    students.put(s2.getId(),s2);;
//    }
    @RequestMapping("list")
    public String list(ModelMap map,Student student){
        if("".equals(student.getName())){
            student.setName(null);
        }
        map.put("studentList",studentService.findAll(student));
        List<Student> students = studentService.findAll(student);
        map.put("studentList",students);
        return "student/list";
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
        System.out.println("id:"+id);
        studentService.deleteById(id);
        return "redirect:/student/list";
    }

    @RequestMapping("create")
    public String create(){
        return "student/create";
    }

    @RequestMapping("save")
    public String save(Student s){
        if(s.getId()==null){
           // s.setId(String.valueOf(students.size()+1));
            s.setId(UUID.randomUUID().toString());
            studentService.save(s);
        }
        System.out.println(s.getName());
        System.out.println(s.getAge());

      //  students.put(s.getId(),s);
        return "redirect:/student/list";
    }
    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map){
        Student s =studentService.getReferenceById(id);

        map.put("student",s);
        return "student/update";
    }
}
